<template>
    <div class="file-uploader">
        <el-upload :on-change="handleFileChange" action="" :show-file-list="false" :auto-upload="false"
            :before-remove="removeFile">
            <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
            <el-button size="small" class="upload-server-btn" :disabled="fileList.length === 0" type="success"
            @click="submitUpload">开始上传</el-button>
        </el-upload>
        <el-table :data="fileList" empty-text="请上传文件">
            <el-table-column prop="name" label="文件名"></el-table-column>
            <el-table-column prop="size" label="文件大小"></el-table-column>
            <el-table-column label="上传进度">
                <template #default="scope">
                    <el-progress :percentage="scope.row.percentage"></el-progress>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
export default {
    data() {
        return {
            fileList: [],
        };
    },
    methods: {
        handleFileChange(file, list) {
            this.fileList = list;
        },
        removeFile(file, list) {
            this.fileList = list;
        },
        async submitUpload() {
            const len = this.fileList.length
            if (len === 0) {
                this.$message.warning('请先选择文件');
                return;
            }
            const userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
            try {
                const res = await this.$axios.post('/carousel/backend/add', {
                    id: userInfo.id,
                    carousel: this.fileList[len - 1].raw,
                }, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                });
                if (res.data.code === 1) {
                    this.$message.success('文件上传成功');
                    this.fileList[len - 1].percentage = 100;
                }
            } catch (error) {
                this.$message.error('文件上传失败');
                console.error(error);
            }
        }
    }
};
</script>

<style scoped>
.file-uploader {
    margin: 20px;
}

.upload-server-btn {
    margin-left: 20px;
} 
.el-table {
    margin-top: 20px;
}
</style>